import { fetchEventSource } from '@microsoft/fetch-event-source'
import { onRequest, onResponseRejected } from './interceptors'

const instance = ({ url, data, onmessage, ...config }) => {
  const baseURL = ''
  let requestUrl = /^http(s)?:\/\//i.test(url) ? url : `${baseURL}/${url.replace(/^\//g, '')}`
  const options = onRequest(config || {})
  console.log('options', options)
  return fetchEventSource(requestUrl, {
    body: JSON.stringify(data),
    onopen(response) {
      if (response.status !== 200) {
        const error = new Error(response.statusText)
        error.config = options
        error.response = response
        onResponseRejected(error)
      }
    },
    onmessage(message) {
      let data = null
      try {
        const value = message.data.replace(/'/g, '"')
        data = JSON.parse(value)
      } catch (err) {
        data = message.data
      }
      onmessage(data)
    },
    onclose(e) {
      console.log(e)
    },
    onerror(err) {
      onResponseRejected(err)
    },
    openWhenHidden: true,
    ...options
  })
}

instance.post = (url, data, config) => {
  return instance({ url, data, method: 'POST', ...config })
}

const useESHttpInstance = () => {
  return instance
}

export default useESHttpInstance
